﻿using Common.UI.Controls.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace Common.UI.Controls
{
	public sealed partial class Absciss : UserControl
	{
		public ObjectSource Source
		{
			get { return (ObjectSource)GetValue(SourceProperty); }
			set { SetValue(SourceProperty, value); }
		}

		public static readonly DependencyProperty SourceProperty =
			DependencyProperty.Register("Source", typeof(ObjectSource), typeof(Absciss), new PropertyMetadata(null, OnSourceChanged));

		private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			(d as Absciss).Update();
		}


		public Absciss()
		{
			this.InitializeComponent();
		}

		private void Update()
		{
			Update(ActualHeight, ActualWidth);
		}

		private void Update(double ActualHeight, double ActualWidth)
		{
			MainGrid.ColumnDefinitions.Clear();

			MainGrid.Children.Clear();

			if (Source == null)
				return;

			var items = Source.Items;

			if (items == null || items.Count() == 0)
				return;

			var index = 0;
			foreach (var item in items)
			{
				var column = new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) };
				MainGrid.ColumnDefinitions.Add(column);

				var tb = new TextBlock()
				{
					HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
					VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center,
					TextAlignment = Windows.UI.Xaml.TextAlignment.Center,
					Foreground = this.Foreground,
					FontSize = this.FontSize,
					Text = item.ToString(),
				};

				MainGrid.Children.Add(tb);
				Grid.SetColumn(tb, index++);
			}

		}

		private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			Update();
		}
	}
}
